1.首先要自定义一个sectionHeadView/sectionFootView继承自 UITableViewHeaderFooterView,如下:
1 2 3 4 5
| #import <UIKit/UIKit.h>
@interface CircleHeaderFooterView : UITableViewHeaderFooterView
@end
|
2.在自定义的sectionHeadView/sectionFootView中重写这个方法,设置复用
1 2 3 4 5 6 7 8 9 10 11 12 13
| #import "CircleHeaderFooterView.h"
@implementation CircleHeaderFooterView
-(instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithReuseIdentifier:reuseIdentifier]; if (self) { } return self; } @end
|
3.在需要调用自定义sectionHeadView/sectionFootView的VC里面调用table的代理方法,用法跟cell的复用相似
1 2 3 4 5 6 7 8 9 10
| - (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ static NSString *viewIdentfier = @"headView"; CircleHeaderFooterView *sectionHeadView = [tableViewdequeueReusableHeaderFooterViewWithIdentifier:viewIdentfier]; if(!sectionHeadView){ sectionHeadView = [[CircleHeaderFooterView alloc]initWithReuseIdentifier:viewIdentfier]; sectionHeadView.contentView.backgroundColor = [UIColor whiteColor]; } return sectionHeadView; }
|
新写法
c1 2 3 4 5 6 7 8 9 10
| 1:注册headerView [self.tableView registerClass:[CircleHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"section"];
2:使用 - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { CircleHeaderFooterView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"section"]; headView.textLabel.text = [NSString stringWithFormat:@"section %ld", section]; return headView; }
|
系统自带
1 2 3 4 5 6 7 8 9 10
| - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UITableViewHeaderFooterView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"section"]; if (!headView) { headView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"section"]; } headView.textLabel.text = [NSString stringWithFormat:@"section %ld", section]; return headView; }
|